package com.whiteape.book.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.whiteape.book.R;
import com.whiteape.book.common.RxEvent;
import com.whiteape.book.contract.HomepageContract;
import com.whiteape.book.core.manager.MediaStorageManager;
import com.whiteape.book.core.manager.ReadSettingManager;
import com.whiteape.book.core.manager.WebMediaManager;
import com.whiteape.book.model.bo.CategoryDetailBo;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.dto.SiteSourceBean;
import com.whiteape.book.model.dto.SiteSourceCategoryBean;
import com.whiteape.book.model.type.HomePageLayoutType;
import com.whiteape.book.model.type.MediaType;
import com.whiteape.book.model.zssq.BookListDetailBean;
import com.whiteape.book.model.zssq.section.HomepageSection;
import com.whiteape.book.presenter.HomepagePresenter;
import com.whiteape.book.ui.activity.MediaDetailActivity;
import com.whiteape.book.ui.activity.SiteCategoryDetailActivity;
import com.whiteape.book.ui.adapter.HomepageChildAdapter;
import com.whiteape.book.ui.adapter.HomepageChooseSourceAdapter;
import com.whiteape.book.ui.base.BaseMVPFragment;
import com.whiteape.book.utils.RxUtils;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.widget.RefreshLayout;
import com.whiteape.book.widget.itemdecoration.DividerItemDecoration;
import com.whiteape.book.widget.itemdecoration.RecyclerViewSpacesItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * 推荐fragment的子fragment
 * 主要是一些书单内容
 */
public class HomepageChildFragment extends BaseMVPFragment<HomepageContract.Presenter> implements HomepageContract.View, BaseQuickAdapter.OnItemChildClickListener {
    @BindView(R.id.refresh_layout)
    RefreshLayout refreshLayout;
    @BindView(R.id.rv_recommend)
    RecyclerView mRvContent;

    @BindView(R.id.rv_choose_site_source)
    RecyclerView rvChooseSiteSource;


    private HomepageChooseSourceAdapter homepageChooseSourceAdapter;
    private List<SiteSourceBean> chooseSourceData = new ArrayList<>();
    //每个书单详情最多展示几个
    private final int MAX_DETAIL_ITEM_COUNT = 4;
    //    private RecommendChildAdapter mRecommendChildAdapter;
    private HomepageChildAdapter mHomepageChildAdapter;
    private List<CategoryDetailBo> data = new ArrayList<>();
    private Map<String, BookListDetailBean> bookListDetailBeanMap = new HashMap<>(20);

    private String tag = "";

    private SiteSourceBean curSiteSourceBean;

    public static Fragment newInstance(String tag) {
        Bundle bundle = new Bundle();
        bundle.putString("tag", tag);
        Fragment fragment = new HomepageChildFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    private void setUpRecyclerView() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 4);

        mRvContent.setLayoutManager(gridLayoutManager);
        if (getContext() != null) {
            mRvContent.addItemDecoration(new DividerItemDecoration(getContext()));
        }
        mHomepageChildAdapter = new HomepageChildAdapter(data);
        mHomepageChildAdapter.setOnItemChildClickListener(this);
        mHomepageChildAdapter.setSpanSizeLookup((gridLayoutManager1, position) -> {
            if (data.get(position).getHomePageShowType() == HomePageLayoutType.HEAD ||
                    data.get(position).getHomePageShowType() == HomePageLayoutType.LIST) {
                return 4;
            }
            return 1;
        });
        mRvContent.setAdapter(mHomepageChildAdapter);
//        mRecommendChildAdapter = new RecommendChildAdapter(R.layout.item_book_list_book_info, R.layout.item_recommend_header, data);
//        if (this.tag.equals(getString(R.string.sex_female))) {
//            mRecommendChildAdapter.addHeaderView(getLayoutInflater().inflate(R.layout.fragment_recommend_child_header_female, null));
//            mRecommendChildAdapter.getHeaderLayout().findViewById(R.id.ll_nav_xiaoyuan).setOnClickListener(this);
//            mRecommendChildAdapter.getHeaderLayout().findViewById(R.id.ll_nav_xianyan).setOnClickListener(this);
//            mRecommendChildAdapter.getHeaderLayout().findViewById(R.id.ll_nav_guyan).setOnClickListener(this);
//            mRecommendChildAdapter.getHeaderLayout().findViewById(R.id.ll_nav_huanyan).setOnClickListener(this);
//        } else {
//            mRecommendChildAdapter.addHeaderView(getLayoutInflater().inflate(R.layout.fragment_recommend_child_header_male, null));
//            mRecommendChildAdapter.getHeaderLayout().findViewById(R.id.ll_nav_xianxia).setOnClickListener(this);
//            mRecommendChildAdapter.getHeaderLayout().findViewById(R.id.ll_nav_dushi).setOnClickListener(this);
//            mRecommendChildAdapter.getHeaderLayout().findViewById(R.id.ll_nav_xuanhuan).setOnClickListener(this);
//            mRecommendChildAdapter.getHeaderLayout().findViewById(R.id.ll_nav_lishi).setOnClickListener(this);
//        }
//        mRecommendChildAdapter.getHeaderLayout().findViewById(R.id.ll_nav_fenlei).setOnClickListener(this);
//
//        mRecommendChildAdapter.setOnItemChildClickListener(this);
//        mRvContent.setAdapter(mRecommendChildAdapter);

    }

    @Override
    public int getContentId() {
        return R.layout.fragment_homepage_child;
    }

    @Override
    protected HomepageContract.Presenter bindPresenter() {
        return new HomepagePresenter();
    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {

    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        if (savedInstanceState != null) {
            tag = savedInstanceState.getString("tag");
        }
        if (getArguments() != null) {
            tag = getArguments().getString("tag");
        }
//        refreshLayout.setColorSchemeColors(ThemeStore.accentColor(MApplication.getInstance()));
//        if (getContext() != null) {
//            refreshLayout.setColorSchemeColors(getContext().getResources().getColor(R.color.colorAccent));
//        }
//        refreshLayout.setOnRefreshListener(() -> {
//            refreshData();
//            refreshLayout.setRefreshing(false);
//        });
        refreshLayout.showLoading();
        setUpRecyclerView();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

        rvChooseSiteSource.setLayoutManager(layoutManager);
        HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
        stringIntegerHashMap.put(RecyclerViewSpacesItemDecoration.RIGHT_DECORATION, 10);//右间距
        RecyclerViewSpacesItemDecoration decoration = new RecyclerViewSpacesItemDecoration(stringIntegerHashMap);
        rvChooseSiteSource.addItemDecoration(decoration);
        rvChooseSiteSource.setAdapter(homepageChooseSourceAdapter);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        homepageChooseSourceAdapter.setOnItemClickListener((adapter, view, position) -> {
                    if (homepageChooseSourceAdapter.getCurSiteSourceBean() != null &&
                            !homepageChooseSourceAdapter.getCurSiteSourceBean().getSiteHostUrl().equals(chooseSourceData.get(position).getSiteHostUrl()))
                        homepageChooseSourceAdapter.setCurSiteSourceBean(chooseSourceData.get(position));
                    homepageChooseSourceAdapter.notifyDataSetChanged();

                    curSiteSourceBean = chooseSourceData.get(position);
//                    setCurrentSiteSourceBean(chooseSourceData.get(position));
                    ReadSettingManager.getInstance().setHomePageSiteHostUrl(curSiteSourceBean.getSiteType(), curSiteSourceBean.getSiteHostUrl());
                    refreshData();
                }
        );
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        homepageChooseSourceAdapter = new HomepageChooseSourceAdapter(R.layout.item_homepage_choose_source, chooseSourceData);
        if (savedInstanceState != null) {
            tag = savedInstanceState.getString("tag");
        }
    }


    /**
     * 首次逻辑操作
     */
    @Override
    protected void startLogic() {
        super.startLogic();
        int type = MediaType.MEDIA_TYPE_NOVEL;
        if (tag.equals(MediaType.getName(MediaType.MEDIA_TYPE_COMIC))) {
            type = MediaType.MEDIA_TYPE_COMIC;
        }
        if (tag.equals(MediaType.getName(MediaType.MEDIA_TYPE_VIDEO))) {
            type = MediaType.MEDIA_TYPE_VIDEO;
        }
        //拿到当前可用的全部网源，填充到上面一栏
        final int curType = type;
        addDisposable(MediaStorageManager.getInstance().getSiteSourceAllInRxWithType(type)
                .compose(RxUtils::toSimpleSingle)
                .subscribe(siteSourceBeanList -> {
                    String savedSiteHostUrl = ReadSettingManager.getInstance().getHomepageSiteHostUrl(curType);
                    for (SiteSourceBean bean : siteSourceBeanList) {
                        if (bean.getSiteCategory() != null) {
                            chooseSourceData.add(bean);
                        }
                    }

                    if (chooseSourceData.size() == 0) {
                        refreshLayout.showEmpty();
                    } else {
                        for (int i = 0; i < chooseSourceData.size(); i++) {
                            SiteSourceBean bean = chooseSourceData.get(i);
                            if (bean.getSiteHostUrl().equals(savedSiteHostUrl)) {
                                curSiteSourceBean = bean;
                                rvChooseSiteSource.scrollToPosition(i > 0 ? i - 1 : i);
                                break;
                            }
                        }
                        if (curSiteSourceBean == null) {
                            curSiteSourceBean = chooseSourceData.get(0);
                        }
                        homepageChooseSourceAdapter.setCurSiteSourceBean(curSiteSourceBean);
                        homepageChooseSourceAdapter.notifyDataSetChanged();
                        refreshData();
                    }


                }, Throwable::printStackTrace));

    }

    public void refreshData() {
        if (mPresenter != null) {
            data.clear();
            mHomepageChildAdapter.notifyDataSetChanged();
            refreshLayout.showLoading();

            if (curSiteSourceBean == null) {
                return;
            }
            //获取分类列表，有的话才去请求，没有的话就算了
            fetchCategoryDetailList(curSiteSourceBean.getSiteHostUrl());
        }
    }

    public void setCurrentSiteSourceBean(SiteSourceBean siteSourceBean) {
        curSiteSourceBean = siteSourceBean;
    }

    @Override
    public void finishRefresh(List<CategoryDetailBo> beanList) {
        if (beanList == null || beanList.isEmpty()) {
            return;
        }
        refreshLayout.showFinish();
        CategoryDetailBo categoryDetailBo = beanList.get(0);
        String categoryName = categoryDetailBo.getCategoryBean().getCategoryName();
        if (categoryName.contains("首页") || categoryName.contains("全部")) {
            categoryDetailBo.getCategoryBean().setCategoryName("重点推荐");
        }
//        beanList.get(0).setHomePageShowType(HomePageLayoutType.HEAD);
        CategoryDetailBo head = new CategoryDetailBo();
        head.setCategoryBean(beanList.get(0).getCategoryBean());
        head.setHomePageShowType(HomePageLayoutType.HEAD);
        data.add(head);
        //如果有图的最多使用MAX_COUNT个
        List<CategoryDetailBo> categoryDetailBoList = new ArrayList<>();
        int count = 0;
        boolean hasDesc = beanList.get(0).getDesc() != null && beanList.get(0).getDesc().trim().length() > 5;
        final int MAX_COUNT = hasDesc ? 5 : 8;
        for (CategoryDetailBo homepageBean : beanList) {
            if (count++ < MAX_COUNT) {// && !StringUtils.isEmpty(homepageBean.getCoverUrl())) {
                categoryDetailBoList.add(homepageBean);
            }
        }
        //如果没图导致不超过MAX_COUNT个的话，最多填充MAX_COUNT个
//        if (categoryDetailBoList.size() < MAX_COUNT) {
//            for (int i = categoryDetailBoList.size(); i < MAX_COUNT && i < beanList.size(); i++) {
//                categoryDetailBoList.add(beanList.get(i));
//            }
//        }

        for (int i = 0; i < categoryDetailBoList.size(); i++) {
            if (hasDesc && i == 0 && !StringUtils.isEmpty(categoryDetailBoList.get(i).getDesc())) {
                categoryDetailBoList.get(i).setHomePageShowType(HomePageLayoutType.LIST);
            } else {
                categoryDetailBoList.get(i).setHomePageShowType(HomePageLayoutType.GRID);
            }
        }
        if (!hasDesc && categoryDetailBoList.size() > 4 && categoryDetailBoList.size() < 8) {
            data.addAll(categoryDetailBoList.subList(0, 4));
        } else {
            data.addAll(categoryDetailBoList);
        }


        mHomepageChildAdapter.notifyDataSetChanged();

    }

    @Override
    public void finishError(Throwable throwable) {
        throwable.printStackTrace();

        refreshLayout.showEmpty();
    }

//    @Override
//    public void upData(BookListDetailBean bookListDetailBean) {
////        this.data = group;
////        mRecommendChildAdapter.setOnLoadMoreListener();
////        upUI();
//    }


    public void upUI() {
//        mRecommendChildAdapter.refreshItems(this.data);
//        mRecommendChildAdapter.s
    }


    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        outState.putString("tag", tag);
        super.onSaveInstanceState(outState);
    }


    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        CategoryDetailBo detailBo = data.get(position);
        if (detailBo.getHomePageShowType() == HomePageLayoutType.HEAD) {
            if (view.getId() == R.id.tv_recommend_header_more) {

                getContext().startActivity(new Intent(getContext(), SiteCategoryDetailActivity.class)
//                    .putExtra(SiteCategoryDetailActivity.KEY_SITE_SOURCE_BEAN, rightData.get(position).t.getSiteSourceBean())
                                .putExtra(SiteCategoryDetailActivity.KEY_SITE_HOST, curSiteSourceBean.getSiteHostUrl())
                                .putExtra(SiteCategoryDetailActivity.KEY_CATEGORY, detailBo.getCategoryBean())
                                .putExtra(SiteCategoryDetailActivity.KEY_CATEGORY_NAME, detailBo.getCategoryBean().getCategoryName())
                                .putExtra(SiteCategoryDetailActivity.KEY_CATEGORY_DETAIL_URL, detailBo.getCategoryBean().getCategoryUrl())
                );
//                Intent intent = new Intent(getContext(), BookRecommendDetailActivity.class);
//                intent.putExtra("data", bookListDetailBeanMap.get(section.header));
//                intent.putExtra("title", section.header);
//                startActivity(intent);
            }
            return;
        }

        //到detail页面，根据当前SiteSourceBean
//        String searchKey = section.t.getTitle();
//        Intent intent = new Intent(getContext(), SearchActivity.class);
//        intent.putExtra("searchKey", searchKey);
//        startActivity(intent);

        CollectionMediaBean collectionMediaBean = new CollectionMediaBean();


        collectionMediaBean.setMediaType(detailBo.getMediaType());
        collectionMediaBean.setAuthor(detailBo.getAuthor());
        collectionMediaBean.setCoverUrl(detailBo.getCoverUrl());
        collectionMediaBean.setId(detailBo.getDetailUrl());
        collectionMediaBean.setCategory(detailBo.getCategory());
        collectionMediaBean.setDesc(detailBo.getDesc());
        collectionMediaBean.setLastChapter(detailBo.getLastChapter());
        collectionMediaBean.setLastUpdated(detailBo.getLastUpdated());
        collectionMediaBean.setState(detailBo.getState());
        collectionMediaBean.setTitle(detailBo.getTitle());
        collectionMediaBean.setWordCount(detailBo.getWordCount());
        collectionMediaBean.setSiteSourceBean(detailBo.getSiteSourceBean());
        collectionMediaBean.setVarMap(detailBo.getVarMap());
//                    collectionMediaBean.setBookSourceUrl();
//                    String bookId = mSearchAdapter.getItem(pos).get_id();
        MediaDetailActivity.startActivity(getContext(), collectionMediaBean, null);

    }

    //首次初始化分类目录索引
    private void initCategoryIndex() {

        addDisposable(WebMediaManager.getInstance().getSourceCategoryIndex(new HashSet<>())
                .compose(RxUtils::toSimpleSingle)
                .subscribe(siteSourceBeanListMap1 -> {
                    for (Map.Entry<SiteSourceBean, List<SiteSourceCategoryBean>> entry : siteSourceBeanListMap1.entrySet()) {
                        MediaStorageManager.getInstance().saveSiteCategory(entry.getValue());
                        RxBus.get().post(RxEvent.SITE_SOURCE_CATEGORY_INDEX_ADDED, entry.getKey().getSiteHostUrl());
                    }
                    ReadSettingManager.getInstance().setCategoryIndexInited(true);

                }, throwable -> throwable.printStackTrace())
        );
    }

//    private void fetchCategoryIndex() {
//        addDisposable(WebMediaManager.getInstance().getSourceCategoryIndex(siteSourceBeanSet)
//                .compose(RxUtils::toSimpleSingle)
//                .subscribe(siteSourceBeanListMap1 -> {
//                    for (Map.Entry<SiteSourceBean, List<SiteSourceCategoryBean>> entry : siteSourceBeanListMap1.entrySet()) {
//                        MediaStorageManager.getInstance().saveSiteCategory(entry.getValue());
//                        RxBus.get().post(RxEvent.SITE_SOURCE_CATEGORY_INDEX_ADDED, entry.getKey().getSiteHostUrl());
//                    }
//
//                }, throwable ->
//                        throwable.printStackTrace()
//
//    });
//}

    private void fetchCategoryDetailList(String siteHostUrl) {
        addDisposable(MediaStorageManager.getInstance()
                .getSiteCategoryBySiteHostUrl(siteHostUrl)
                .compose(RxUtils::toSimpleSingle)
                .subscribe(beanList -> {
                    if (beanList == null || beanList.isEmpty()) {
//                        refreshLayout.showEmpty();
                        //TODO 这里去请求一次
                        if (!ReadSettingManager.getInstance().getIfCategoryIndexInited()) {
                            initCategoryIndex();
                        }

                        return;
                    }

                    mPresenter.refreshHomepageData(curSiteSourceBean, beanList);

                }, throwable -> {
                    throwable.printStackTrace();
                    refreshLayout.showEmpty();

                }));


    }

    @Subscribe(thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxEvent.SITE_SOURCE_CATEGORY_INDEX_ADDED)
            })
    public void onSiteCategoryIndexAdded(String siteHostUrl) {
        if (StringUtils.isEmpty(siteHostUrl)) {
            return;
        }
        if (curSiteSourceBean != null && curSiteSourceBean.getSiteHostUrl().equals(siteHostUrl)) {
            //拿到该网源的分类索引
            refreshData();
        }

    }

    @Subscribe(thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxEvent.SITE_SOURCE_ADDED),
                    @Tag(RxEvent.SITE_SOURCE_DELETED)
            })
    public void onSiteSourceChanged(String siteSourceUrl) {
        if (curSiteSourceBean != null && curSiteSourceBean.getSiteHostUrl().equals(siteSourceUrl)) {

            startLogic();

        }

    }
}
